package org.chen.task;

import lombok.extern.slf4j.Slf4j;
import org.chen.model.sys.ImageResource;
import org.chen.service.impl.ConfigServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

@Component
@Slf4j
public class ImageCleanupTask {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 每天凌晨3点执行清理
     */
    @Scheduled(cron = "0 0 3 * * ?")
    public void cleanupDeletedImages() {
        log.info("Starting cleanup of deleted images...");
        try {
            // 查找所有标记为已删除的图片
            Query query = Query.query(Criteria.where("isDeleted").is(true));
            List<ImageResource> deletedImages = mongoTemplate.find(query, ImageResource.class);

            if (deletedImages.isEmpty()) {
                log.info("No deleted images found to cleanup");
                return;
            }

            log.info("Found {} deleted images to cleanup", deletedImages.size());
            int successCount = 0;
            int failureCount = 0;

            for (ImageResource image : deletedImages) {
                try {
                    // 删除物理文件
                    File file = new File(image.getPath());
                    if (file.exists() && file.delete()) {
                        // 从数据库中彻底删除记录
                        mongoTemplate.remove(
                            Query.query(Criteria.where("id").is(image.getId())),
                            ImageResource.class
                        );
                        successCount++;
                    } else {
                        log.warn("Failed to delete file: {}", file.getAbsolutePath());
                        failureCount++;
                    }
                } catch (Exception e) {
                    log.error("Error deleting image {}: {}", image.getId(), e.getMessage());
                    failureCount++;
                }

                // 每处理100个记录打印一次进度
                if ((successCount + failureCount) % 100 == 0) {
                    log.info("Processed {}/{} images", (successCount + failureCount), deletedImages.size());
                }
            }

            log.info("Image cleanup completed. Success: {}, Failure: {}", successCount, failureCount);

        } catch (Exception e) {
            log.error("Error during image cleanup task", e);
        }
    }

    /**
     * 手动触发清理
     */
    public void manualCleanup() {
        cleanupDeletedImages();
    }
}